# bank_app.py
import streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import warnings, os, sys
warnings.filterwarnings('ignore')

# -------------------- 基础配置 --------------------
plt.rcParams['font.sans-serif'] = ['SimHei']          # 中文
plt.rcParams['axes.unicode_minus'] = False            # 负号
plt.rcParams['figure.facecolor'] = 'none'             # 透明背景

st.set_page_config(
    page_title="银行业务数据分析系统",
    page_icon=":chart_with_upwards_trend:",
    layout="wide",
    initial_sidebar_state="expanded"
)

# -------------------- 政务统一样式 --------------------
CUSTOM_CSS = """
<style>
body{font-family:"Microsoft YaHei","SimSun",sans-serif;background:#f0f2f5;color:#333;}
[data-testid="stSidebar"]{background:#fff;border-right:1px solid #d0d5d9;padding:15px;}
[data-testid="stSidebar"] h3{color:#0052d9;font-size:16px;font-weight:600;
border-bottom:1px solid #d0d5d9;padding-bottom:8px;margin-bottom:15px;}
.stButton>button{background:#0052d9;color:#fff;border:none;border-radius:0;
padding:8px 24px;font-weight:600;}
.stButton>button:hover{background:#003b8c;}
h1,h2,h3,h4{color:#0052d9;font-weight:600;}
.main-header{background:#0052d9;color:#fff;padding:20px;text-align:center;margin-bottom:20px;}
.section-card{background:#fff;border:1px solid #d0d5d9;border-left:3px solid #0052d9;
padding:20px;margin-bottom:20px;box-shadow:0 1px 3px rgba(0,0,0,.05);}
.metric-card{background:#fff;border:1px solid #d0d5d9;border-left:4px solid #0052d9;
padding:15px;text-align:center;box-shadow:0 1px 2px rgba(0,0,0,.08);}
.metric-value{font-size:24px;font-weight:bold;color:#0052d9;margin-bottom:5px;}
.metric-label{font-size:14px;color:#5e6e7e;font-weight:500;}
</style>
"""
st.markdown(CUSTOM_CSS, unsafe_allow_html=True)

# -------------------- 数据加载 --------------------
# 首先添加文件上传功能
st.sidebar.subheader("上传数据文件")
atm_file = st.sidebar.file_uploader("上传 ATM 数据文件 (atm.csv)", type="csv")
branch_file = st.sidebar.file_uploader("上传 柜面 数据文件 (branch.csv)", type="csv")

@st.cache_data(ttl=3600)
def load_data(atm_file=None, branch_file=None):
    try:
        # 如果用户上传了文件，使用上传的文件
        if atm_file is not None:
            atm = pd.read_csv(atm_file, nrows=10000)
        else:
            # 否则尝试读取默认文件
            atm = pd.read_csv('atm.csv', nrows=10000)
        
        if branch_file is not None:
            branch = pd.read_csv(branch_file, nrows=10000)
        else:
            branch = pd.read_csv('branch.csv', nrows=10000)
        
        atm['交易日期'] = pd.to_datetime(atm['交易日期'], format='%Y%m%d')
        branch['交易日期'] = pd.to_datetime(branch['交易日期'], format='%Y%m%d')
        return atm, branch
    except Exception as e:
        st.error(f"数据加载失败：{e}")
        return None, None

atm_df, branch_df = load_data(atm_file, branch_file)

# -------------------- 侧边栏 --------------------
with st.sidebar:
    st.markdown('<div class="main-header"><h2>筛选条件</h2></div>', unsafe_allow_html=True)
    if atm_df is not None and branch_df is not None:
        min_date = min(atm_df['交易日期'].min(), branch_df['交易日期'].min())
        max_date = max(atm_df['交易日期'].max(), branch_df['交易日期'].max())
        start_date, end_date = st.date_input("分析时间段", value=(min_date, max_date),
                                            min_value=min_date, max_value=max_date)
        # 设备类型
        atm_df['设备类型'] = atm_df['设备编号'].apply(lambda x: 'VTM' if isinstance(x, str) and 'VTM' in x else 'ATM')
        dev_types = ['全部'] + sorted(atm_df['设备类型'].unique())
        dev_sel = st.selectbox("ATM设备类型", dev_types)
        if st.button("应用筛选", type="primary", use_container_width=True):
            st.experimental_rerun()
    else:
        st.stop()

# -------------------- 数据筛选 --------------------
atm_f = atm_df[(atm_df['交易日期'] >= pd.Timestamp(start_date)) &
               (atm_df['交易日期'] <= pd.Timestamp(end_date))]
branch_f = branch_df[(branch_df['交易日期'] >= pd.Timestamp(start_date)) &
                     (branch_df['交易日期'] <= pd.Timestamp(end_date))]
if dev_sel != '全部':
    atm_f = atm_f[atm_f['设备类型'] == dev_sel]

# -------------------- 页面标题 --------------------
st.markdown('<div class="main-header"><h1>银行业务数据分析系统</h1>'
            '<p>ATM与柜面业务运营分析</p></div>', unsafe_allow_html=True)

# -------------------- Tab 构造 --------------------
tab1, tab2, tab3 = st.tabs(["数据概览", "ATM业务分析", "柜面业务分析"])

# -------------------- 1. 数据概览 --------------------
with tab1:
    st.subheader("数据统计概览")
    col1, col2 = st.columns(2)
    
    # ATM 指标
    with col1:
        st.markdown("<div class='section-card'><h3>ATM业务指标</h3></div>", unsafe_allow_html=True)
        c1, c2 = st.columns(2)
        c1.metric("交易笔数", f"{len(atm_f):,}")
        atm_total = atm_f['现金存款'].sum() + atm_f['现金取款'].sum()
        c2.metric("总交易金额", f"¥{atm_total:,.0f}")
    
    # 柜面指标
    with col2:
        st.markdown("<div class='section-card'><h3>柜面业务指标</h3></div>", unsafe_allow_html=True)
        c3, c4 = st.columns(2)
        c3.metric("交易笔数", f"{len(branch_f):,}")
        branch_total = branch_f['柜面现金存款'].sum() + branch_f['柜面现金取款'].sum()
        c4.metric("总交易金额", f"¥{branch_total:,.0f}")
    


# -------------------- 2. ATM 分析 --------------------
with tab2:
    st.subheader("ATM业务分析")
    col1, col2, col3 = st.columns(3)
    col1.metric("交易笔数", f"{len(atm_f):,}")
    col2.metric("设备数量", f"{atm_f['设备编号'].nunique():,}")
    col3.metric("所属机构数", f"{atm_f['所属机构'].nunique():,}")

    # 设备类型饼图
    st.markdown("---")
    fig, ax = plt.subplots(figsize=(3, 2.5))
    type_counts = atm_f['设备类型'].value_counts()
    ax.pie(type_counts, labels=type_counts.index, autopct='%1.1f%%', startangle=90)
    ax.set_title("ATM设备类型分布")
    st.pyplot(fig)

    # 现金业务
    cash_sum = atm_f[['现金存款', '现金取款']].sum()
    fig, ax = plt.subplots(figsize=(4, 2.5))
    cash_sum.plot(kind='bar', ax=ax, color=['#0052d9', '#007bff'])
    ax.set_title("ATM现金业务总金额"); ax.set_ylabel("元")
    st.pyplot(fig)

# -------------------- 3. 柜面分析 --------------------
with tab3:
    st.subheader("柜面业务分析")
    c1, c2 = st.columns(2)
    c1.metric("交易笔数", f"{len(branch_f):,}")
    c2.metric("机构数量", f"{branch_f['机构编号'].nunique():,}")

    # 机构 TOP8
    st.markdown("---")
    top_branch = branch_f['机构名称'].value_counts().head(8)
    fig, ax = plt.subplots(figsize=(4, 3))
    top_branch.plot(kind='barh', ax=ax, color='#0052d9')
    ax.set_title("柜面交易笔数TOP8机构")
    st.pyplot(fig)

    # 现金业务
    cash_sum_br = branch_f[['柜面现金存款', '柜面现金取款']].sum()
    fig, ax = plt.subplots(figsize=(4, 2.5))
    cash_sum_br.plot(kind='bar', ax=ax, color=['#0052d9', '#38a169'])
    ax.set_title("柜面现金业务总金额"); ax.set_ylabel("元")
    st.pyplot(fig)